package avicit.bdp.dcs.job.service;

import avicit.bdp.common.base.BaseService;
import avicit.bdp.common.utils.BdpLogUtil;
import avicit.bdp.common.utils.CheckParaUtils;
import avicit.bdp.core.util.json.JSONUtils;
import avicit.bdp.dcs.datasource.dto.JobDatasource;
import avicit.bdp.dcs.datasource.service.DataSourceUtils;
import avicit.bdp.dcs.datasource.service.TableService;
import avicit.bdp.dcs.job.dao.DcsJobDao;
import avicit.bdp.dcs.job.dto.JobDTO;
import avicit.bdp.dcs.precheck.service.PrecheckService;
import avicit.bdp.dcs.task.dto.TableMappingDto;
import avicit.bdp.dcs.task.service.TaskService;
import avicit.bdp.dcs.utils.DcsConstants;
import avicit.bdp.dcs.utils.DcsErrorCode;
import avicit.bdp.dcs.utils.JdbcConstants;
import avicit.platform6.core.exception.BusinessException;
import org.apache.commons.collections4.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @金航数码科技有限责任公司
 * @作者：liyb
 * @邮箱：liyb@avic-digital.com
 * @创建时间： 2023-04-07 15:53
 * @类说明： 文件采集服务类
 * @修改记录：
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class FileJobService extends BaseService<DcsJobDao, JobDTO> implements JobInterface {

  private static final Logger logger = LoggerFactory.getLogger(FileJobService.class);

  @Autowired private TaskService taskService;
  @Autowired private PrecheckService precheckService;

  /** 验证数据 */
  private void checkData(JobDTO newJobDTO) throws Exception {
    // 判断参数合法性
    CheckParaUtils.checkStringValidity(newJobDTO.getTransferType(), logger, "迁移类型必填");
    CheckParaUtils.checkObjectValidity(newJobDTO.getProcessMode(), logger, "已存在表的处理模式必填");
    CheckParaUtils.checkStringValidity(newJobDTO.getSelectedTable(), logger, "待同步模板必填");
    CheckParaUtils.checkStringValidity(newJobDTO.getSelectedFile(), logger, "待同步文件必填");
  }

  /**
   * 作业配置第二步(保存表映射关系)
   *
   * @throws Exception
   */
  @Override
  public void saveTableMapping(JobDTO oldJobDTO, JobDTO newJobDTO) throws Exception {
    // 验证数据
    checkData(newJobDTO);

    // 记录日志
    BdpLogUtil.log4Update(newJobDTO, oldJobDTO);

    // 1、 更新Job信息
    this.updateByPrimaryKeySelective(newJobDTO);

    // 2、批量新增或修改任务
    taskService.saveTasksByJob(oldJobDTO.getId());

    // 3、新增预检查信息(先删除再新增)
    precheckService.saveJobPrecheck(oldJobDTO.getId());
  }

}
